package com.jf.cloud.service.sysmanager.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie工具类 封装Cookie常用操作
 */
public class CookieHelper {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(CookieHelper.class);
	
	/**
	 * Cookie有效期，7天
	 */
	private final static int COOKIE_MAX_AGE_7D = 60 * 60 * 24 * 7;

	/**
	 * Cookie有效期，14天
	 */
	private final static int COOKIE_MAX_AGE_14D = 60 * 60 * 24 * 14;

	/**
	 * WebSSO 域名
	 */
	private final static String WebSSOdomainName = ".3yx.com";
	
	/**
	 * WebSSO Cookie 名称
	 */
	public final static String WebSSOcookieName = "www.3yx.com_WebSSOID";
	/**
	 * WebSSO Cookie 名称
	 */
	public static final String ADMIN_WEB_SSO_COOKIE_NAME = "www.juefeng.com_WebSSOID";

	/**
	 * 3yx用户登录MD5键
	 */
	private final static String I3YX_LOGIN_MD5_KEY = "i3yx_user_login_md5";

	/**
	 * 3yx用户登录Cookie键
	 */
	private final static String I3YX_LOGIN_COOKIE_KEY = "i3yx_user_login_cookie";

	/**
	 * 删除指定Cookie
	 * 
	 * @author 程伟平 创建时间：2013-11-08 11:25:22
	 */
	public static void removeCookie(HttpServletResponse response, Cookie cookie) {
		if (cookie != null) {
			cookie.setPath("/");// 网站根目录
			cookie.setValue("");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}

	/**
	 * 删除指定Cookie
	 * 
	 * @author 程伟平 创建时间：2013-11-08 11:25:22
	 */
	public static void removeCookie(HttpServletResponse response, Cookie cookie, String domain) {
		if (cookie != null) {
			cookie.setPath("/");// 网站根目录
			cookie.setValue("");
			cookie.setMaxAge(0);
			cookie.setDomain(domain);
			response.addCookie(cookie);
		}
	}

	/**
	 * 根据Cookie名称得到Cookie值，若不存在则返回NULL
	 * 
	 * @author 程伟平 创建时间：2013-11-08 11:25:22
	 */
	public static String getCookieValue(HttpServletRequest request, String name) {
		Cookie cookie = getCookie(request, name);
		if (cookie != null) {
			return cookie.getValue();
		}
		return null;
	}

	/**
	 * 根据Cookie名称得到Cookie对象，若不存在则返回NULL
	 * 
	 * @author 程伟平 创建时间：2013-11-08 11:25:22
	 */
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie cookies[] = request.getCookies();
		if (name == null || name.length() == 0 || cookies == null || cookies.length == 0) {
			return null;
		}
		Cookie cookie = null;
		for (int i = 0; i < cookies.length; i++) {
			if (!cookies[i].getName().equals(name)) {
				continue;
			}
			cookie = cookies[i];
			if (request.getServerName().equals(cookie.getDomain())) {
				break;
			}
		}
		return cookie;
	}

	/**
	 * 设置一条新Cookie，默认有效时间7天
	 * 
	 * @author 程伟平 创建时间：2013-11-08 11:25:22
	 */
	public static void setCookie(HttpServletResponse response, String name, String value) {
		setCookie(response, name, value, COOKIE_MAX_AGE_7D);
	}

	/**
	 * 设置一条新Cookie，有效时间(单位：秒)
	 * 
	 * @author 程伟平 创建时间：2013-11-08 11:25:22
	 */
	public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
		if (value == null) {
			value = "";
		}
		Cookie cookie = new Cookie(name, value);
		if (maxAge != 0) {
			cookie.setMaxAge(maxAge);
		} else {
			cookie.setMaxAge(COOKIE_MAX_AGE_7D);
		}
		cookie.setPath("/"); // 网站根目录
		response.addCookie(cookie);
	}

	/**
	 * 获取WebSSO用户登录Cookie
	 * 
	 * @author 程伟平 创建时间：2013-11-08 14:35:05
	 */
	public static Cookie getWebSSOCookie(HttpServletRequest request) {
		return getCookie(request, WebSSOcookieName);
	}

	/**
	 * 设置WebSSO用户登录Cookie
	 * 
	 * @author 程伟平 创建时间：2013-11-08 14:35:05
	 */
	public static void setWebSSOCookie(String ticket, HttpServletResponse response) {
		try {
			Cookie cookie = new Cookie(WebSSOcookieName, ticket);
			cookie.setDomain(WebSSOdomainName);
			cookie.setPath("/");
			cookie.setMaxAge(-1); // 关闭浏览器即失效
			// cookie.setMaxAge(60*60); // 有效期 60分钟
			response.addCookie(cookie);
		} catch (Exception e) {
			log.error("设置WebSSO用户登录Cookie出错了！", e);
		}
	}

	/**
	 * 删除WebSSO用户登录Cookie
	 * 
	 * @author 程伟平 创建时间：2013-11-08 11:25:22
	 */
	public static void removeWebSSOCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie cookie = getCookie(request, WebSSOcookieName);
		if (cookie != null) {
			cookie.setDomain(WebSSOdomainName);
			cookie.setPath("/");// 网站根目录
			cookie.setValue("");
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}

	/**
	 * 设置用户登录Cookie
	 * 
	 * @author 程伟平 创建时间：2013-11-08 14:35:05
	 */
	public static void setLoginUserInCookie(String userAccount, HttpServletResponse response) {
		try {
			// 有效期
			long validTime = System.currentTimeMillis() + (60 * 60 * 24 * 7 * 1000);
			String cookieValueMd5 = MD5.encode(userAccount + ":" + validTime + ":" + I3YX_LOGIN_MD5_KEY);
			
			String cookieValue = SecurityEncoder.encode(userAccount + ":" + validTime + ":" + cookieValueMd5);
			
			CookieHelper.setCookie(response, I3YX_LOGIN_COOKIE_KEY, cookieValue, COOKIE_MAX_AGE_14D);
		} catch (Exception e) {
			log.error("设置用户登录Cookie出错了！", e);
		}
	}

	/**
	 * 根据Cookie获取登录用户
	 * 
	 * @author 程伟平 创建时间：2013-11-08 14:35:05
	 */
	public static String getLoginUserInCookie(HttpServletRequest request, HttpServletResponse response) {
		String userAccount = null;

		try {
			String cookieValue = getCookieValue(request, I3YX_LOGIN_COOKIE_KEY);
			if (cookieValue != null && cookieValue.length() > 0) {
				cookieValue = SecurityEncoder.decode(cookieValue);
				String[] cookieValues = cookieValue.split(":");
				if (cookieValues.length == 3) {
					// MD5码校验
					String md5ValueByUser = MD5.encode(cookieValues[0] + ":" + cookieValues[1] + ":" + I3YX_LOGIN_MD5_KEY);
					if (!md5ValueByUser.equals(cookieValues[2])) {
						return null;
					}
					// 有效期校验
					long validTimeByCookie = Long.valueOf(cookieValues[1]);
					if (validTimeByCookie >= System.currentTimeMillis()) {
						userAccount = cookieValues[0];
					} else {
						removeCookie(response, new Cookie(I3YX_LOGIN_COOKIE_KEY, null));
					}
				}
			}
		} catch (Exception e) {
			log.error("根据Cookie获取登录用户出错了！", e);
		}
		return userAccount;
	}
	

}
